package cn.ailanyin.home.module.login.service.impl;

import cn.ailanyin.home.common.exception.ServiceException;
import cn.ailanyin.home.common.utils.JwtUtil;
import cn.ailanyin.home.common.utils.Sm4Util;
import cn.ailanyin.home.module.login.eneity.dto.LoginDTO;
import cn.ailanyin.home.module.login.eneity.dto.RegisterDTO;
import cn.ailanyin.home.module.login.service.LoginService;
import cn.ailanyin.home.module.user.entity.User;
import cn.ailanyin.home.module.user.service.UserService;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 登录服务
 *
 * @author ailanyin
 * @date 2024/04/13
 */
@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {

    private final UserService userService;

    @Override
    public String login(LoginDTO dto) {
        User user = userService.selectByUsername(dto.getUsername());
        if (Objects.isNull(user)) {
            throw new ServiceException("用户名不存在！");
        }

        // 判断密码
        String realPwd = Sm4Util.decrypt(user.getPassword());
        if (!StrUtil.equals(realPwd, dto.getPassword())) {
            throw new ServiceException("密码错误！");
        }
        // 返回Token
        return JwtUtil.generateToken(user.getId(), user.getUsername(), user.getHomeId(), user.getNickname());
    }

    @Override
    public void register(RegisterDTO dto) {
        User user = new User();
        user.setNickname(StrUtil.isBlank(dto.getNickname()) ? RandomUtil.randomString(8) : dto.getNickname());
        user.setUsername(dto.getUsername());
        // 加密密码
        user.setPassword(Sm4Util.encrypt(dto.getPassword()));
        user.setHomeId(StrUtil.isBlank(dto.getHomeId()) ? RandomUtil.randomNumbers(6) : dto.getHomeId());
        userService.insert(user);
    }


}
